package com.useeinfo.oa.open.admin;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.data.SelectVO;
import com.useeinfo.framework.sugar.func.excel.ExcelExport;
import com.useeinfo.framework.sugar.func.file.FileUtils;
import com.useeinfo.framework.sugar.tools.Configuration;
import com.useeinfo.framework.sugar.tools.QRCodeUtil;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.common.config.ConstantKeyFilePath;
import com.useeinfo.oa.common.config.ExcelExportMap;
import com.useeinfo.oa.common.utils.ResultUtil.ResultDto;
import com.useeinfo.oa.common.utils.ResultUtil.ResultUtil;
import com.useeinfo.oa.modules.base.biz.*;
import com.useeinfo.oa.modules.base.entity.Enterprise;
import com.useeinfo.oa.modules.base.entity.Facility;
import com.useeinfo.oa.modules.base.entity.FacilityCat;
import com.useeinfo.oa.modules.base.entity.Resource;
import com.useeinfo.oa.modules.base.enums.ResourceTypeEnum;
import com.useeinfo.oa.modules.logger.biz.FacilityLogBiz;
import com.useeinfo.oa.modules.logger.entity.FacilityLog;
import com.useeinfo.oa.modules.logger.enums.LogTypeEnum;
import com.useeinfo.oa.modules.repair.entity.RepairOrder;
import com.useeinfo.oa.modules.security.biz.OrganizationBiz;
import com.useeinfo.oa.modules.security.entity.SystemUser;
import com.useeinfo.oa.modules.security.util.SessionKeyUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @Auther: bin.liu
 * @Date: 2018/12/5 13:32
 * @Description: 设备管理action
 */
@Controller
@RequestMapping("/web/admin/facility")
public class FacilityManageAction {

    @Autowired
    private FacilityBiz facilityBiz;
    @Autowired
    private FacilityCatBiz facilityCatBiz;
    @Autowired
    private FacilityGroupBiz facilityGroupBiz;
    @Autowired
    private AreaBiz areaBiz;
    @Autowired
    private ResourceBiz resourceBiz;
    @Autowired
    private OrganizationBiz organizationBiz;
    @Autowired
    private FacilityLogBiz facilityLogBiz;

    @RequestMapping("/list")
    public ModelAndView list() {

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("pages/admin/facility/facilityList");

        return modelAndView;
    }

    @RequestMapping("/listJson")
    @ResponseBody
    public JSONObject listJson(@RequestParam(value = "pageNo", required = false) String pageNowParam,
                               @RequestParam(value = "pageSize", required = false) String pageSizeParam,
                               @RequestParam(value = "searchCode", required = false) String searchCode,
                               @RequestParam(value = "likeName", required = false) String likeName,
                               @RequestParam(value = "areaName", required = false) String areaName,
                               @RequestParam(value = "rootCatName", required = false) String rootCatName,
                               @RequestParam(value = "facilityGroup", required = false) String facilityGroup,
                               @RequestParam(value = "facilityCatName", required = false) String facilityCatName,
                               @RequestParam(value = "orderBy", required = false) String orderBy,
                               HttpServletRequest request) {
        QueryParam queryParam = new QueryParam(pageNowParam, pageSizeParam);
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if (enterprise != null) {
            queryParam.getSqlMap().put("enterpriseId", enterprise.getId() + "");
        }
        if(StringUtils.isNotBlank(searchCode)){
            queryParam.getSqlMap().put("likeCode", searchCode);
        }
        if(StringUtils.isNotBlank(likeName)){
            queryParam.getSqlMap().put("likeName", likeName);
        }
        if(StringUtils.isNotBlank(areaName)){
            queryParam.getSqlMap().put("areaName", areaName);
        }
        if(StringUtils.isNotBlank(facilityGroup)){
            queryParam.getSqlMap().put("facilityGroup", facilityGroup);
        }
        if(StringUtils.isNotBlank(rootCatName)){
            String facilityCatIds = facilityCatBiz.getFacilityCatIdsByNameLike(rootCatName,
                    enterprise == null ? "" : StringConverters.null2String(enterprise.getId()));
            queryParam.getSqlMap().put("facilityCatIds", facilityCatIds);
        }
        if(StringUtils.isNotBlank(facilityCatName)){
            queryParam.getSqlMap().put("facilityCatName", facilityCatName);
        }
        if (StringUtils.isNotBlank(orderBy)) {
            queryParam.setSqlOrder("order by " + orderBy);
        }
        JSONObject jsonObject = facilityBiz.findJSONList(queryParam);
        JSONArray jsonArray = jsonObject.getJSONArray("list");
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject json = jsonArray.getJSONObject(i);
            Long catId = json.getLong("facilityCatId");
            json.put("rootCatName","");
            if(catId!=null){
                FacilityCat rootCat = facilityCatBiz.findRootCat(catId);
                if(rootCat!=null){
                    json.put("rootCatName",rootCat.getCatName());
                }
            }
        }
        return jsonObject;
    }

    @RequestMapping("/editPage")
    public ModelAndView editPage(@RequestParam(value = "id", required = false) String id, HttpServletRequest request) {

        ModelAndView modelAndView = new ModelAndView();
        Facility facility = facilityBiz.findModel(StringConverters.null2Long(id));
        modelAndView.addObject("facility", facility);
        //二维码显示专用
        String qrCodeString = "";

        String fieldPhotoStr = "";
        String platePhotoStr = "";
        String rootCatId = "";
        if (facility != null) {
            if (StringUtils.isNotBlank(facility.getQrCode())) {
                qrCodeString = facility.getQrCode();
            } else if (StringUtils.isNotBlank(facility.getCode())) {
                qrCodeString = facility.getCode();
            }
            //图片专用
            if (facility.getFieldPhoto() != null && facility.getFieldPhoto().size() != 0) {
                List<Resource> resourceList = new ArrayList<Resource>(facility.getFieldPhoto());
                fieldPhotoStr = Configuration.getConfigurationByName("hostUrl") + resourceList.get(0).getPath();
            }
            if (facility.getPlatePhoto() != null && facility.getPlatePhoto().size() != 0) {
                List<Resource> resourceList = new ArrayList<Resource>(facility.getPlatePhoto());
                platePhotoStr = Configuration.getConfigurationByName("hostUrl") + resourceList.get(0).getPath();

            }
            //设备专业专用
            if (facility.getFacilityCat() != null) {
                FacilityCat rootCat = facilityCatBiz.findRootCat(facility.getFacilityCat().getId());
                rootCatId = rootCat.getId() + "";
            }
        }
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        modelAndView.addObject("enterprise", enterprise);
        modelAndView.addObject("rootCatId", rootCatId);
        modelAndView.addObject("qrCodeString", qrCodeString);
        modelAndView.addObject("fieldPhoto", fieldPhotoStr);
        modelAndView.addObject("platePhoto", platePhotoStr);
        modelAndView.setViewName("pages/admin/facility/facilityEdit");

        return modelAndView;
    }

    /**
     * 获取编辑页面（新增复制）
     */
    @RequestMapping("/copyEditPage")
    public ModelAndView copyEditPage(@RequestParam(value = "id", required = false) String id, HttpServletRequest request){
        ModelAndView modelAndView = new ModelAndView();
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(request);
        if (sessionEnterprise != null) {
            modelAndView.addObject("enterprise", sessionEnterprise);
        }
        Facility facility = facilityBiz.findModel(StringConverters.null2Long(id));

        //二维码显示专用
        String qrCodeString = "";
        String fieldPhotoPath = "";
        String platePhotoPath = "";
        String rootCatId = "";
        if (facility != null) {
            if (StringUtils.isNotBlank(facility.getQrCode())) {
                qrCodeString = facility.getQrCode();
            } else if (StringUtils.isNotBlank(facility.getCode())) {
                qrCodeString = facility.getCode();
            }
            //现场照片
            if (facility.getFieldPhoto() != null && facility.getFieldPhoto().size() != 0) {
                List<Resource> resourceList = new ArrayList<Resource>(facility.getFieldPhoto());
                fieldPhotoPath = Configuration.getConfigurationByName("hostUrl") + resourceList.get(0).getPath();
            }
            //铭牌照片
            if (facility.getPlatePhoto() != null && facility.getPlatePhoto().size() != 0) {
                List<Resource> resourceList = new ArrayList<Resource>(facility.getPlatePhoto());
                platePhotoPath = Configuration.getConfigurationByName("hostUrl") + resourceList.get(0).getPath();

            }
            //设备专业专用
            if (facility.getFacilityCat() != null) {
                FacilityCat rootCat = facilityCatBiz.findRootCat(facility.getFacilityCat().getId());
                rootCatId = rootCat.getId() + "";
            }
            facility.setSerialCode(facilityBiz.getSerialCode(sessionEnterprise.getId()+""));
            facility.setId(null);
        }


        modelAndView.addObject("facility", facility);
        modelAndView.addObject("enterprise", sessionEnterprise);
        modelAndView.addObject("rootCatId", rootCatId);
        modelAndView.addObject("qrCodeString", qrCodeString);
        modelAndView.addObject("fieldPhoto", fieldPhotoPath);
        modelAndView.addObject("platePhoto", platePhotoPath);
        modelAndView.setViewName("pages/admin/facility/facilityEdit");
        return modelAndView;
    }

    @RequestMapping("/addOrUpdate")
    @ResponseBody
    public ResultDto addOrUpdate(Facility facility) {
        facilityBiz.addOrUpdate(facility);
        return ResultUtil.success();
    }

    /**
     * 执行提交的新增或修改请求
     */
    @RequestMapping("/executeFacilityEdit")
    @ResponseBody
    public ResultDto executeFacilityEdit(Facility facility,
                                         @RequestParam(value = "selectCatId[]", required = false) List<String> selectCatIds,
                                         @RequestParam(value = "selectRootCatId[]", required = false) List<String> selectRootCatIds,
                                         @RequestParam(value = "selectGroupId[]", required = false) List<String> selectGroupIds,
                                         @RequestParam(value = "selectAreaId[]", required = false) List<String> selectAreaIds,
                                         @RequestParam(value = "selectParentId[]", required = false) List<String> selectParentIds,
                                         @RequestParam(value = "selectOrganizationId[]", required = false) List<String> selectOrganizationIds,
                                         @RequestParam(value = "sImg1", required = false) String sImg1,
                                         @RequestParam(value = "sImg2", required = false) String sImg2,
                                         @RequestParam(value = "pic1", required = false) MultipartFile pic1,
                                         @RequestParam(value = "pic2", required = false) MultipartFile pic2,
                                         @RequestParam(value = "longitude1", required = false) String longitudeParam,
                                         @RequestParam(value = "latitude1", required = false) String latitudeParam,
                                         HttpServletRequest request) {

        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if (enterprise == null) {
            return ResultUtil.error("获取企业失败，请更新页面重试");
        }
        SystemUser systemUser = SessionKeyUtils.getSessionUser(request);
        if (systemUser == null) {
            return ResultUtil.error("获取用户信息失败，请更新页面重试");
        }
        if(StringUtils.isBlank(facility.getQrCode())){
            facility.setQrCode(facility.getCode());
        }
        if (facilityBiz.existFacility(facility, enterprise.getId())) {
            return ResultUtil.error("您输入的设备编号/二维码已存在，请重新输入");
        }
        //判断经纬度
        if (StringUtils.isNotBlank(longitudeParam)) {
            Double longitude;
            try {
                longitude = Double.parseDouble(longitudeParam);
            } catch (Exception e) {
                return ResultUtil.error("经度格式有误，请重新输入");
            }
            if (longitude > 180D || longitude < -180D) {
                return ResultUtil.error("经度格式有误，请重新输入");
            }
            facility.setLongitude(longitude);
        }
        if (StringUtils.isNotBlank(latitudeParam)) {
            Double latitude;
            try {
                latitude = Double.parseDouble(latitudeParam);
            } catch (Exception e) {
                return ResultUtil.error("纬度格式有误，请重新输入");
            }
            if (latitude > 90D || latitude < -90D) {
                return ResultUtil.error("纬度格式有误，请重新输入");
            }
            facility.setLatitude(latitude);
        }
        if(selectRootCatIds!=null &&selectCatIds == null){
            return ResultUtil.error("请选择设备类型，或取消选择设备专业");
        }
        if (CollectionUtils.isNotEmpty(selectCatIds)) {
            FacilityCat facilityCat = facilityCatBiz.findModel(StringConverters.ToLong(selectCatIds.get(0)));
            if(facilityCat!=null&&facilityCat.getLvl()!=0){
                facility.setFacilityCat(facilityCat);
                facility.setRootCatId(facilityCatBiz.findRootCat(facilityCat.getId()).getId());
            }
        }
        if (CollectionUtils.isNotEmpty(selectGroupIds)) {
            facility.setFacilityGroup(facilityGroupBiz.findModel(StringConverters.ToLong(selectGroupIds.get(0))));
        }
        if (CollectionUtils.isNotEmpty(selectAreaIds)) {
            facility.setArea(areaBiz.findModel(StringConverters.ToLong(selectAreaIds.get(0))));
        }
        if (CollectionUtils.isNotEmpty(selectOrganizationIds)) {
            facility.setOrganization(organizationBiz.findModel(StringConverters.ToLong(selectOrganizationIds.get(0))));
        }
        if (CollectionUtils.isNotEmpty(selectParentIds) && !StringConverters.ToLong(selectParentIds.get(0)).equals(facility.getId())) {
            Facility parentFacility = facilityBiz.findModel(StringConverters.ToLong(selectParentIds.get(0)));
            if(parentFacility!=null){
                facility.setParentId(parentFacility.getId());
                facility.setParentName(parentFacility.getName());
            }
        }

        //现场图片操作
        if ("1".equals(sImg1)) {
            //首先删除之前的关联图片
            facility.setFieldPhoto(null);
            //如果有新图片 再存新图片
            String savePath1 = FileUtils.fileUpload(pic1, ConstantKeyFilePath.FACILITY_IMG_DIR, ConstantKeyFilePath.FACILITY_IMG_FIX, Configuration.getConfigurationByName("fileSaveRootPath"));
            if (StringUtils.isNotEmpty(savePath1)) {
                Resource resource = new Resource();
                resource.setPath(savePath1);
                resource.setResourceName("设备现场图片");
                resource.setResourceTypeEnum(ResourceTypeEnum.IMG);
                resourceBiz.addOrUpdate(resource);
                Set<Resource> resourceSet = new HashSet<>();
                resourceSet.add(resource);
                facility.setFieldPhoto(resourceSet);
            }
        } else {
            if (facility.getId() != null) {
                facility.setFieldPhoto(facilityBiz.findModel(facility.getId()).getFieldPhoto());
            }
        }
        //铭牌图片操作
        if ("1".equals(sImg2)) {
            //首先删除之前的关联图片
            facility.setPlatePhoto(null);
            //如果有新图片 再存新图片
            String savePath2 = FileUtils.fileUpload(pic2, ConstantKeyFilePath.FACILITY_IMG_DIR, ConstantKeyFilePath.FACILITY_IMG_FIX, Configuration.getConfigurationByName("fileSaveRootPath"));
            if (StringUtils.isNotEmpty(savePath2)) {
                Resource resource = new Resource();
                resource.setPath(savePath2);
                resource.setResourceName("设备铭牌图片");
                resource.setResourceTypeEnum(ResourceTypeEnum.IMG);
                resourceBiz.addOrUpdate(resource);
                Set<Resource> resourceSet = new HashSet<>();
                resourceSet.add(resource);
                facility.setPlatePhoto(resourceSet);
            }
        } else {
            if (facility.getId() != null) {
                facility.setPlatePhoto(facilityBiz.findModel(facility.getId()).getPlatePhoto());
            }
        }

        facility.setEnterprise(enterprise);
        if(facility.getId()==null){
            facility.setSerialCode(facilityBiz.getSerialCode(enterprise.getId()+""));
        }
        //添加设备日志
        FacilityLog facilityLog = new FacilityLog();
        if (facility.getId() == null) {
            facilityLog.setLogTypeEnum(LogTypeEnum.insert);
        } else {
            facilityLog.setLogTypeEnum(LogTypeEnum.update);
        }
        facilityLog.setUserName(systemUser.getUserName());
        facilityLog.setUserId(systemUser.getId());
        facilityBiz.addOrUpdate(facility);
        facilityLog.setFacilityId(facility.getId());
        facilityLogBiz.addOrUpdate(facilityLog);
        return ResultUtil.success();
    }

    /**
     * 获取系统模块选择数据
     *
     * @param q
     * @return
     */
    @RequestMapping("/getFacilitySelect")
    @ResponseBody
    public List<SelectVO> getFacilitySelect(@RequestParam(value = "q", required = false) String q,
                                            @RequestParam(value = "id", required = false) String id,
                                            HttpServletRequest request) {
        //下面保证默认选择项加载正常
        String index = "";
        boolean status = false;//表示默认list中无此id的数据
        Facility facility = facilityBiz.findModel(StringConverters.ToLong(id));
        if(StringUtils.isBlank(q)&&facility!=null){
            index = id;
        }
        List<SelectVO> selectVOS = new ArrayList<>();
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("likeName", q);
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if (enterprise != null) {
            queryParam.getSqlMap().put("enterpriseId", enterprise.getId() + "");
        }
        List<Facility> facilityList = facilityBiz.findList(queryParam);
        if(CollectionUtils.isNotEmpty(facilityList)){
            for(Facility facility1 : facilityList){
                if(StringUtils.isNotBlank(index)&&index.equals(facility1.getId()+"")){
                    status = true;
                }
                selectVOS.add(new SelectVO(facility1.getName(), facility1.getId() + ""));
            }
        }
        if(!status&&facility!=null){
            selectVOS.add(new SelectVO(facility.getName(), facility.getId() + ""));
        }
        return selectVOS;
    }

    /**
     * 根据设备编号选择数据,用于维修模块
     *
     * @param q
     * @return
     */
    @RequestMapping("/getFacilitySelectByCode")
    @ResponseBody
    public List<SelectVO> getFacilitySelectByCode(@RequestParam(value = "q", required = false) String q,
                                            @RequestParam(value = "id", required = false) String id,
                                            HttpServletRequest request) {
        //下面保证默认选择项加载正常
        String index = "";
        boolean status = false;//表示默认list中无此id的数据
        Facility facility = facilityBiz.findModel(StringConverters.ToLong(id));
        if(StringUtils.isBlank(q)&&facility!=null){
            index = id;
        }
        List<SelectVO> selectVOS = new ArrayList<>();
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("likeName", q);
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if (enterprise != null) {
            queryParam.getSqlMap().put("enterpriseId", enterprise.getId() + "");
        }
        List<Facility> facilityList = facilityBiz.findList(queryParam);
        if(CollectionUtils.isNotEmpty(facilityList)){
            for(Facility facility1 : facilityList){
                if(StringUtils.isNotBlank(index)&&index.equals(facility1.getId()+"")){
                    status = true;
                }
                selectVOS.add(new SelectVO(facility1.getCode(), facility1.getId() + ""));
            }
        }
        if(!status&&facility!=null){
            selectVOS.add(new SelectVO(facility.getCode(), facility.getId() + ""));
        }
        return selectVOS;
    }


    /**
     * 设备导出
     */
    @RequestMapping(value = "/exportFacility", produces = {"text/plain;charset=UTF-8"})
    @ResponseBody
    public void exportFacility(HttpServletResponse response, HttpServletRequest request) {
        String searchCode = "";
        String likeName = "";
        String areaName = "";
        String rootCatName = "";
        String facilityCatName = "";
        try {
            searchCode = URLDecoder.decode(request.getParameter("searchCode"), "UTF-8");
            likeName = URLDecoder.decode(request.getParameter("likeName"), "UTF-8");
            areaName = URLDecoder.decode(request.getParameter("areaName"), "UTF-8");
            rootCatName = URLDecoder.decode(request.getParameter("rootCatName"), "UTF-8");
            facilityCatName = URLDecoder.decode(request.getParameter("facilityCatName"), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        QueryParam queryParam = new QueryParam();
        SystemUser systemUser = SessionKeyUtils.getSessionUser(request);
        if (systemUser == null) {
            return;
        }
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if (enterprise != null) {
            queryParam.getSqlMap().put("enterpriseId", enterprise.getId() + "");
        }
        queryParam.getSqlMap().put("likeCode", searchCode);
        queryParam.getSqlMap().put("likeName", likeName);
        queryParam.getSqlMap().put("areaName", areaName);
        if(StringUtils.isNotBlank(rootCatName)){
            String facilityCatIds = facilityCatBiz.getFacilityCatIdsByNameLike(rootCatName,
                    enterprise == null ? "" : StringConverters.null2String(enterprise.getId()));
            queryParam.getSqlMap().put("facilityCatIds", facilityCatIds);
        }
        if(StringUtils.isNotBlank(facilityCatName)){
            queryParam.getSqlMap().put("facilityCatName", facilityCatName);
        }
        List<Facility> facilityList = facilityBiz.findList(queryParam);
        JSONArray jsonArray = new JSONArray();
        if (CollectionUtils.isNotEmpty(facilityList)) {
            for (Facility facility : facilityList) {
                JSONObject json = facility.toDetailJSONObject();
                FacilityCat rootCat = facilityCatBiz.findModel(facility.getRootCatId());
                if(rootCat!=null){
                    json.put("rootCatId",rootCat.getId());
                    json.put("rootCatName",rootCat.getCatName());
                }
                jsonArray.add(json);
            }
        }
        try {
            ExcelExport.exportExcelFile("设备清单", ExcelExportMap.FACILITY_LIST_EXPORT_MAP(), jsonArray, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //添加设备日志
        FacilityLog facilityLog = new FacilityLog();
        facilityLog.setLogTypeEnum(LogTypeEnum.exportExcel);
        facilityLog.setUserName(systemUser.getUserName());
        facilityLog.setUserId(systemUser.getId());
        facilityLog.setContent("[导出参数] " + "[likeCode:" + searchCode + "],[likeName:" + likeName + "],[areaName:" + areaName + "],[rootCatName:" + rootCatName + "],[facilityCatName:" + facilityCatName + "]");
        facilityLogBiz.addOrUpdate(facilityLog);
    }

    @RequestMapping(value = "/getAreaId")
    @ResponseBody
    public JSONObject getAreaId(String facilityId) {
        String id = "";
        Facility facility = facilityBiz.findModel(StringConverters.null2Long(facilityId));
        if (facility.getArea() != null) {
            id = StringConverters.null2String(facility.getArea().getId());
        }
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("areaId",id);
        jsonObject.put("facilityName",facility.getName());
        return jsonObject;
    }
    @RequestMapping(value = "/getMajorName")
    @ResponseBody
    public JSONObject getMajorName(String facilityId){
        JSONObject result = new JSONObject();
        result.put("majorName","");
        Facility facility = facilityBiz.findModel(StringConverters.null2Long(facilityId));
        Long rootCatId = facility.getRootCatId();
        if(rootCatId != null){
            result.put("majorName",facilityCatBiz.findModel(rootCatId).getCatName());
            result.put("majorId",rootCatId);
        }
        return result;
    }
    //获取设备地址，拼接
    @RequestMapping(value = "/getPosition")
    @ResponseBody
    public JSONObject getPosition(String facilityId){
        JSONObject result = new JSONObject();
        result.put("position","");
        Facility facility = facilityBiz.findModel(StringConverters.null2Long(facilityId));
        if(facility != null){
            result.put("position",StringConverters.null2String(facility.getPosition())+StringConverters.null2String(facility.getPrecisePosition())+StringConverters.null2String(facility.getDetailPosition()));
        }
        return result;
    }

    @RequestMapping(value = "/getQRCodeImageUrl")
    public void getQRCodeImageUrl(@RequestParam(value = "id", required = false) String facilityId,HttpServletResponse response) {
        Facility facility = facilityBiz.findModel(StringConverters.null2Long(facilityId));
        String qrCode = facility.getCode();
        if(StringUtils.isNotBlank(facility.getQrCode())){
            qrCode = facility.getQrCode();
        }
        String imgName = facility.getEnterprise().getId()+"-"+facility.getCode()+"-"+StringConverters.null2String(facility.getName())+".png";
        response.setContentType("application/octet-stream");
        response.addHeader("Content-Disposition", "attachment;filename="+imgName);
        response.setCharacterEncoding("utf-8");
        OutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            QRCodeUtil.writeToStream(qrCode,outputStream,1000,1000);
            outputStream.write(new byte[1024 * 1024]);
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 设备启用
     * @param id
     */
    @RequestMapping(value = "/startUsing")
    @ResponseBody
    public ResultDto startUsing(@RequestParam(value = "id", required = false) String id) {
        Facility facility = facilityBiz.findModel(StringConverters.null2Long(id));
        if(facility == null){
            return ResultUtil.error("无此设备");
        }
        facility.setStop(false);
        facilityBiz.addOrUpdate(facility);
        return ResultUtil.success();
    }

    /**
     * 设备停用
     * @param id
     */
    @RequestMapping(value = "/stopUsing")
    @ResponseBody
    public ResultDto stopUsing(@RequestParam(value = "id", required = false) String id) {
        Facility facility = facilityBiz.findModel(StringConverters.null2Long(id));
        if(facility == null){
            return ResultUtil.error("无此设备");
        }
        facility.setStop(true);
        facilityBiz.addOrUpdate(facility);
        return ResultUtil.success();
    }
}
